package calculator.controller;/*
 * @author     ：zhangbo
 * @date       ：Created in 2021/5/22 12:45
 * @description：负责处理用户单击保存按钮触发的ActionEvent事件。
 * @modified By：zhangbo
 * @version:     $
 */

import calculator.view.CalculatorWindows;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.*;

public class HandleFile extends HandleEvent {
    public HandleFile(CalculatorWindows window) {
        super(window);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == window.copyButton)
            window.saveComputerProcess.copy();
        if (e.getSource() == window.clearTextButton)
            window.saveComputerProcess.setText(null);
       if (e.getSource() == window.saveButton) {
            JFileChooser chooser = new JFileChooser();
            int state = chooser.showSaveDialog(null);
            File file = chooser.getSelectedFile();
            if (file != null && state == JFileChooser.APPROVE_OPTION){
                try {
                    String content = window.saveComputerProcess.getText();
                    StringReader read = new StringReader(content);
                    BufferedReader in = new BufferedReader(read);
                    FileWriter outOne = new FileWriter(file);
                    BufferedWriter out = new BufferedWriter(outOne);
                    String str = null;
                    while ((str = in.readLine()) != null) {
                        out.write(str);
                        out.newLine();
                    }
                    in.close();
                    out.close();
                } catch (IOException ignored) {
                }
            }
        }
    }
}
